package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private static final ExecutorService SECKILL_EXECUTOR = Executors.newSingleThreadExecutor();

    private IVoucherOrderService proxy;


    @PostConstruct
    private void init(){
        SECKILL_EXECUTOR.submit(new VoucherOrderHandler());

    }

    private class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    //1.获取队列中的订单
                    VoucherOrder voucherOrder = orderTasks.take();
                    //2.处理订单
                    handleVoucherOrder(voucherOrder);
                        
                } catch (Exception e) {
                    log.error("处理订单失败");
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //使用Redisson锁
        RLock lock = redissonClient.getLock("lock:order" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock){
            //获取锁失败，放回错误信息
            log.error("处理订单失败");
            return;
        }
        //获取锁成功,创建优惠券订单
        try {
            proxy.creatVoucher(voucherOrder);
        } finally {
            //释放锁
            lock.unlock();
        }
    }


    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        //SECKILL_SCRIPT 中 通过lua脚本的原子性解决了超卖问题,使用Redis中的set解决了一人一单的问题
        /*
            result返回值为
            1:库存不足获取下单资格失败
            2:重复下单,获取下单资格失败
            0:获取下单资格成功
         */

        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue();
        //判断执行结果
        if (r != 0){
            //如果不为0，则下单失败
            return Result.fail(r == 1 ? "库存不足":"不能重复下单");
        }
        //为0，具有下单资格
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //1.设置订单id
        Long orderId = redisIdWorker.getID("order");
        voucherOrder.setId(orderId);
        //2.设置用户id
        voucherOrder.setUserId(userId);
        //3.设置优惠券id
        voucherOrder.setVoucherId(voucherId);

        //将订单信息放入到阻塞队列
        orderTasks.add(voucherOrder);
        //获取代理对象（事务）
        proxy = (IVoucherOrderService) AopContext.currentProxy();


        return Result.ok(orderId);

    }

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //查询优惠券信息
//        SeckillVoucher voucher = iSeckillVoucherService.getById(voucherId);
//        //判断秒杀是否开始
//        if (LocalDateTime.now().isBefore(voucher.getBeginTime())){
//            return Result.fail("秒杀尚未开始");
//        }
//        //判断秒杀是否结束
//        if (LocalDateTime.now().isAfter(voucher.getEndTime())){
//            return Result.fail("秒杀已经结束");
//        }
//        Long userId = UserHolder.getUser().getId();
//        //创建锁对象
//        //SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        //尝试获取锁
//        //boolean isLock = simpleRedisLock.tryLock(5L);
//
//        //使用Redisson锁
//        RLock lock = redissonClient.getLock("lock:order" + userId);
//        boolean isLock = lock.tryLock();
//        if (!isLock){
//            //获取锁失败，直接放回错误信息
//            return Result.fail("不允许重复下单");
//        }
//        //获取锁成功,创建优惠券订单
//        try {
//            // 获取当前代理对象，用于自调用
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            // 调用创建优惠券订单的方法
//            return proxy.creatVoucher(voucherId,voucher);
//        } finally {
//            //释放锁
//            lock.unlock();
//        }
//    }

    @Transactional
    public void creatVoucher(VoucherOrder voucherOrder){
        Long userId =voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        int count = query().eq("user_id", userId).eq("voucher_id",voucherId).count();
        if (count > 0){
            log.error("用户已经购买过一次了");
            return;
        }
        //扣减库存
        boolean success = iSeckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock",0)//乐观锁
                .update();
        if (!success){
            log.error("库存不足");
            return;
        }
        save(voucherOrder);
    }
}
